/*
 * @Date         : 2024-05-14 17:06:56 星期2
 * @Author       : xut
 * @Description  :
 */
import { resolve } from "node:path"
import grpc from "@grpc/grpc-js"
import { loadProto } from "../utils/loadProto.js"

function unaryEchoCall(client, message) {
  return new Promise((resolve, reject) => {
    const deadline = new Date()
    deadline.setSeconds(deadline.getSeconds() + 1) // 请求超时 1 s

    client.unaryEcho({ message }, { deadline }, (err, res) => {
      if (err) {
        console.log(`[Client] Error: ${JSON.stringify(err)}`)
      } else {
        console.log("Client Received: ", JSON.stringify(res))
      }
      resolve()
    })
  })
}

async function run() {
  const PROTO_PATH = resolve(process.cwd(), "./echo.proto")
  const echoProtoDescriptor = loadProto(PROTO_PATH)
  const echoProto = echoProtoDescriptor.echo
  const client = new echoProto.Echo(
    "localhost:50051",
    grpc.credentials.createInsecure()
  )

  await unaryEchoCall(client, "正常响应")
  console.log("==============================")
  await unaryEchoCall(client, "delay: 超时")
}

run()
